<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c_rt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jstl/fmt_rt"  prefix="fmt_rt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ page language="java" 
	import="java.util.*" 
	import="com.jp.fm.data.*"
	pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
	<head>
    	<base href="<%=basePath%>">
    
    	<title>HFM: Transactions</title>
		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
	 
 		<link rel="stylesheet" href="jquery-ui-1.10.0.custom/css/cupertino/jquery-ui-1.10.0.custom.css" />
		<script src="jquery-ui-1.10.0.custom/js/jquery-1.9.0.js"></script>
  		<script src="jquery-ui-1.10.0.custom/js/jquery-ui-1.10.0.custom.js"></script>
  		<script src='js/jquery.number.min.js'></script>
 
  		<link rel="stylesheet" href="css/fm.css" />	
  		
  		<style type="text/css">
    
    		fieldset { padding:0; border:0; margin-top:25px; }
		    div#composite-transaction-contain { width: 700px; margin: 20px 0; }
		    div#composite-transaction-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
		    div#composite-transaction-contain table td, div#composite-transaction-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
		    .ui-dialog .ui-state-error { padding: .3em; }
		    .validateTips { border: 1px solid transparent; padding: 0.3em; }
 		</style>
  		  	  	
  		<script type="text/javascript">
  		$(function() {
    	$( "#accordion" ).accordion();
  		});
  		
  		$(function() {
    		$( "#startDateDatepicker" ).datepicker({
      			showOn: "button",
      			buttonImage: "images/calendar.gif",
      			buttonImageOnly: true
    		});
  		});
  		
   		$(function() {
    		$( "#endDateDatepicker" ).datepicker({
      			showOn: "button",
      			buttonImage: "images/calendar.gif",
      			buttonImageOnly: true
    		});
  		});
  		  		
  		$(function() {
  			var transactionAmount = $( "#transactionAmount" ),
		    	transactionCategory = $( "#transactionCategory" ),
		    	transactionNote = $( "#transactionNote" ),
      			allCompositeTrasactionFields = $( [] ).add( transactionAmount ).add( transactionCategory ).add( transactionNote ),
      			transactionCompositeText = $( ".transactionCompositeText" ),
      			addedCompositeTransactionCount = 0;
      			
			//$("#transactionAmount").number( true, 2 );      						
  		  		
  			function addCompositeTransaction() {
        
	    		var bValid = true;
	        	allCompositeTrasactionFields.removeClass( "ui-state-error" );
	        	
	        	// TODO: validate that the amount from each child adds up to the total of the parent transaction. 
	        	
	        	// Replace single quotes with escaped version.
	        	var encodedNote = escape(transactionNote.val());
	        	alert(encodedNote);
  
		        if ( bValid ) {
		        
		          $( "#compositeTransactionTable tbody" ).append( "<tr id=composite_row_id_new" + addedCompositeTransactionCount + ">" +
		            "<td>" + $.number(transactionAmount.val(), 2) + "</td>" +
		            "<td>" + transactionCategory.find(":selected").text() + "</td>" +
		            "<td>" + transactionNote.val() + "</td>" +		            
		          "</tr>" );  
		          
		          $( "#composite-transaction" ).append(
		            "<input type='hidden' name='comp_tran_amt_" + addedCompositeTransactionCount + "' id='comp_tran_amt_" + addedCompositeTransactionCount + "' value='" + transactionAmount.val() + "' />" +
					"<input type='hidden' name='comp_tran_category_" + addedCompositeTransactionCount + "' id='comp_tran_category_" + addedCompositeTransactionCount + "' value='" + transactionCategory.val() + "' />" +
					"<input type='hidden' name='comp_tran_note_" + addedCompositeTransactionCount + "' id='comp_tran_note_" + addedCompositeTransactionCount + "' value='" + encodedNote + "' />");
		                    		          		          
		          allCompositeTrasactionFields.val( "" );
		          addedCompositeTransactionCount++;
		        } 
	    	}  		
  		
	  		$("#addTransactionButton").click(addCompositeTransaction);
	  		
	  		$( "#dialog-form-composite-transaction" ).dialog({
	      		autoOpen: false,
		      	height: 400,
		      	width: 720,
		      	modal: true,
		      	buttons: [
		      		{
		      			id: "save-button",        
		        		text: "Save",
		        		click: function() {
		        			$("#composite-transaction").trigger('submit');
		        			$( this ).dialog( "close" );		        		
		        			location.reload();
		        		}	        		
		        	},
		        	{
		        		id: "cancel-button",        
		        		text: "Cancel",
		        		click: function() {
		          			$( this ).dialog( "close" );
		        		}
		        	}
		      	],
		      	close: function() {
		        	allCompositeTrasactionFields.val( "" ).removeClass( "ui-state-error" );
		        	$( "#compositeTransactionTable tbody tr" ).remove();		        	
		        	$( "#composite-transaction input" ).remove();
		        	addedCompositeTransactionCount = 0;
		      	}
		   	 });
	 		
	 		$('.open-composite-transaction-dialog').click(function(){
	 			 			
	 			// If view only then remove the Save button
	 			if("View" == $(this).text()) {
	 				$("#save-button").attr("disabled", true);
	 			}
	 			
	 			var transId = $(this).attr('id');
	 			transId = transId.substring(0, transId.indexOf('Tran'));
	 			var transCatId = $("#" + transId + "Cat").val();
	 			var transCatName = $("#" + transId + "CatName").val();
	 			var transAmt = $("#" + transId + "Amt").val();	 			
	 			var transCompId, transCompCatId, transCompCatName, transCompAmt, transCompNote;	 	
	 			
	 			transactionCompositeText.text(transCatName + " $" + $.number(transAmt, 2));
	 			$( "#composite-transaction" ).append("<input type='hidden' name='comp_tran_parent_" + transId + "' id='comp_tran_parent_" + transId + "' value='" + transId + "' />");	
	 			
	 			addedCompositeTransactionCount = 0; 			
	 			
	 			$('input[value|=' + transId + ']').each(function(index) {		 				
	 				if($(this).filter("[id$='CompTranParentId']").length > 0) {	 					   						
   						transCompId = $(this).attr('id');
   						transCompId = transCompId.substring(0, transCompId.indexOf('CompTranParentId'));
   						
   						transCompCatId = $("#" + transCompId + "CompTranCatId").val();
   						transCompCatName = $("#" + transCompId + "CompTranCatName").val();
   						transCompAmt = $("#" + transCompId + "CompTranAmt").val();
   						transCompNote = $("#" + transCompId + "CompTranNote").val();
   						
   						$( "#compositeTransactionTable tbody" ).append( "<tr id=composite_row_id_" + transId + "_" + addedCompositeTransactionCount + ">" +
		            		"<td>" + $.number(transCompAmt, 2) + "</td>" +
		            		"<td>" + transCompCatName + "</td>" +		            
		            		"<td>" + transCompNote + "</td>" +
		          			"</tr>" );
		          			
		          		$( "#composite-transaction" ).append(
		            		"<input type='hidden' name='comp_tran_amt_" + addedCompositeTransactionCount + "' id='comp_tran_amt_" + addedCompositeTransactionCount + "' value='" + transCompAmt + "' />" +
							"<input type='hidden' name='comp_tran_category_" + addedCompositeTransactionCount + "' id='comp_tran_category_" + addedCompositeTransactionCount + "' value='" + transCompCatId + "' />" + 
							"<input type='hidden' name='comp_tran_note_" + addedCompositeTransactionCount + "' id='comp_tran_note_" + addedCompositeTransactionCount + "' value='" + transCompNote + "' />");		          			
		          			
		          		addedCompositeTransactionCount++; 
   					}
 				});	 			
	 		
				$( "#dialog-form-composite-transaction" ).dialog( "open" );
			});
			
			// variable to hold request
			var request;
			// bind to the submit event of our form
			$("#composite-transaction").submit(function(event){				
			    // abort any pending request
			    if (request) {
			        request.abort();
			    }
			    // setup some local variables
			    var $form = $(this);
			    // let's select and cache all the fields
			    var $inputs = $form.find("input, select, button, textarea");
			    // serialize the data in the form
			    var serializedData = $form.serialize();
			
			    // let's disable the inputs for the duration of the ajax request
			    $inputs.prop("disabled", true);
			
			    // fire off the request to /form.php
			    var request = $.ajax({
			        url: "/fm/secured/SaveTransactions",
			        type: "post",
			        async: false,
			        data: serializedData
			    });
			
			    // callback handler that will be called on success
			    request.done(function (response, textStatus, jqXHR){
			        
			        alert(response);
			    });
			
			    // callback handler that will be called on failure
			    request.fail(function (jqXHR, textStatus, errorThrown){
			        // log the error to the console
			        alert(
			            "The following error occured: "+
			            textStatus, errorThrown
			        );
			    });
			
			    // callback handler that will be called regardless
			    // if the request failed or succeeded
			    request.always(function () {
			        // reenable the inputs
			        $inputs.prop("disabled", false);
			    });
			
			    // prevent default posting of form
			    event.preventDefault();
			});			

		}); 		
  		</script> 
  		  		   
	</head>
	<body>
		<c:set var="saveButtonDisabled" scope="page" value="true"/>
  		<div id="page" class="page">


	    	<jsp:include page='Header.jsp' flush="true" />

			<div id="main" class="main">		
			
				<jsp:include page='LeftBar.jsp' flush="true" />		   
		    	
		    	<div id="mainbody" class="mainbody">
		    		    	
		    		<div id="bodycontent" class="bodycontent">
		    			<div id="searchDiv" class="section">
		    			<form id="searchForm" action="/fm/secured/ShowTransactions" method="post">
						  <fieldset><legend></legend>
						    <label for="searchCategory">Category</label>
						    <select name="searchCategory" id="searchCategory" > 	
    							<c:forEach var="cat" items = "${allCategories}">
									<option value="<c:out value='${cat.id}' />"<c:if test="${cat.name eq category}">selected="selected"</c:if>><c:out value='${cat.name}' /></option>
								</c:forEach>										
							</select>
							<label for="startDateDatepicker">Start Date</label>
						    <input type="text" name="startDateDatepicker" id="startDateDatepicker" class="text ui-widget-content ui-corner-all" style="width: 80px;"/>
							<label for="endDateDatepicker">End Date</label>
						    <input type="text" name="endDateDatepicker" id="endDateDatepicker" class="text ui-widget-content ui-corner-all" style="width: 80px;"/>
						    <label for="keyword">Keywords</label>						    						    						    
						    <input type="text" name="keyword" id="keyword" class="text ui-widget-content ui-corner-all" style="width: 80px;"/>						    
						    <input type="submit" name="search" id="searchButton" value="Search" 
						    	class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />	
						  </fieldset>
						  <c:forEach var="itm" items="${o}">
							<input type="hidden" name="o" id="o" value="<c:out value='${itm}' />" />
        				  </c:forEach>
						  </form>
		    			</div>
		    			
		    			<div class="section">
		    				<form id="saveTransactionCategory" action="/fm/secured/SaveTransactions" method="post">
		    				<h2>
		    				<c:choose>
		    					<c:when test="${empty account.name}">
		    						<span class="textleft"><c:out value='${category}' escapeXml='false'/></span>
		    						<span class="textleft">
		    							<fmt:formatDate pattern="MMMM dd, yyyy" value="${startDate}" /> 
		    							<c:if test="${!empty startDate and !empty endDate}"> - </c:if> 
		    							<fmt:formatDate pattern="MMMM dd, yyyy" value="${endDate}" /></span>
		    							<span class="textleft"><c:out value='${keyword}' escapeXml='false'/></span>
		    						<span class="textright"><fmt:formatNumber value='${categoryAmount}' type='currency' /></span>
		    					</c:when>
		    					<c:otherwise>
		    						<span class="textleft"><c:out value='${account.name}' escapeXml='false'/></span>
		    						<span class="textright">Balance: <fmt:formatNumber value='${account.balance}' type='currency' /></span>
		    						<span class="rewards-fees-right">
		    							<c:if test="${!empty rewards}">Rewards YTD: <fmt:formatNumber value='${rewards}' type='currency' /></c:if>
		    							<c:if test="${!empty rewards and !empty fees}"><br/></c:if>
		    							<c:if test="${!empty fees}">Fees/Interest YTD: <fmt:formatNumber value='${fees}' type='currency' /></c:if>
		    						</span>
		    					</c:otherwise>
		    				</c:choose>
		    				</h2>
		    				<table id="myTable" class="ui-widget ui-widget-content dialogtable">			
								<thead>
									<tr class="ui-widget-header">
										<th class="">Account</th>
										<th class="">Date</th>										
										<th class="">Amount</th>
										<th class="">Category</th>
										<th class='no-sort'>Description</th>
										<th class="no-sort">Composite Transaction</th>				
									</tr>
								</thead>
								<tbody>
									<c:set var="counter" scope="page" value="0"/>
									<c:forEach var="tran" items = "${trans}">
										<tr>
											<td class="contenttext" nowrap="true"><c:out value='${tran.account}' escapeXml='false'/>&nbsp;&nbsp;&nbsp;</td>
											<td class="contenttext" nowrap="true"><c:out value='${tran.date}' escapeXml='false'/></td>										
											<td class="contenttext" nowrap="true"><fmt:formatNumber value='${tran.amount}' type='currency' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
											<input type="hidden" name="transactionId_<c:out value='${counter}' />" value="<c:out value='${tran.id}' />"/>
											<input type="hidden" name="transEditable_<c:out value='${counter}' />" value="<c:choose><c:when test="${tran.category.name ne 'Unknown' and tran.confirmed}">false</c:when><c:otherwise><c:set var="saveButtonDisabled" value="false"/>true</c:otherwise></c:choose>"/>
											<td class="contenttext">
												<select name="cat_<c:out value='${counter}' />" <c:if test="${tran.category.name ne 'Unknown' and tran.confirmed}">disabled="true"</c:if> id="cat_<c:out value='${counter}' />" value="<c:out value='${tran.category.name}' />"> 
												<c:forEach var="cat" items = "${allCategories}">
													<option value="<c:out value='${cat.id}' />" <c:if test="${cat.id eq tran.category.id}"><c:out value='selected="selected"' /></c:if>><c:out value='${cat.name}' escapeXml='false'/></option>
												</c:forEach>
												<c:out value='${tran.category.name}' />
												</select>
											</td>
											<td class="contenttext"><a class="click-link" url="/fm/secured/ShowTransactions?searchTransactionId=<c:out value='${tran.id}' />"><c:out value='${tran.description}' escapeXml='false'/></a>
												<c:if test="${!empty tran.note}"><img border="0" src="images/note.gif" alt="note" width="12" height="12"></c:if>
											</td>
											<td class="contenttext">
												<c:choose>												
												<c:when test="${not tran.confirmed}">																											
													<a class="open-composite-transaction-dialog" id="<c:out value='${tran.id}' />Tran">Edit</a>
												</c:when>
												<c:when test="${fn:length(tran.compositeTransactions) gt 0}">
													<a class="open-composite-transaction-dialog" id="<c:out value='${tran.id}' />Tran">View</a>
												</c:when>
												</c:choose>
												<input type="hidden" id="<c:out value='${tran.id}' />Cat" value="<c:out value='${tran.category.id}' />" />
												<input type="hidden" id="<c:out value='${tran.id}' />CatName" value="<c:out value='${tran.category.name}' />" /> 
												<input type="hidden" id="<c:out value='${tran.id}' />Amt" value="<c:out value='${tran.amount}' />" />
												<input type="hidden" id="<c:out value='${tran.id}' />Note" value="<c:out value='${tran.note}' />" />
											</td>
										</tr>	
										<c:set var="counter" scope="page" value="${counter+1}"/>
<%-- 

Start child transaction section

--%>										
										<c:forEach var="compTran" items = "${tran.compositeTransactions}">
										<tr>
											<td class="contenttext" nowrap="true">--><c:out value='${compTran.account}' escapeXml='false'/>&nbsp;&nbsp;&nbsp;</td>
											<td class="contenttext" nowrap="true"><c:out value='${compTran.date}' escapeXml='false'/></td>										
											<td class="contenttext" nowrap="true"><fmt:formatNumber value='${compTran.amount}' type='currency' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
											<input type="hidden" name="transactionId_<c:out value='${counter}' />" value="<c:out value='${compTran.id}' />"/>
											<input type="hidden" name="transEditable_<c:out value='${counter}' />" value="<c:choose><c:when test="${compTran.category.name ne 'Unknown' and compTran.confirmed}">false</c:when><c:otherwise><c:set var="saveButtonDisabled" value="false"/>true</c:otherwise></c:choose>"/>
											<td class="contenttext">
												<select name="cat_<c:out value='${counter}' />"<c:if test="${compTran.category.name ne 'Unknown' and compTran.confirmed}">disabled="true"</c:if> id="cat_<c:out value='${counter}' />" value="<c:out value='${compTran.category.name}' />"> 
												<c:forEach var="cat" items = "${allCategories}">
													<option value="<c:out value='${cat.id}' />" <c:if test="${cat.id eq compTran.category.id}"><c:out value='selected="selected"' /></c:if>><c:out value='${cat.name}' escapeXml='false'/></option>
												</c:forEach>
												<c:out value='${compTran.category.name}' />
												</select>
											</td>
											<td class="contenttext"><c:out value='${compTran.description}' escapeXml='false'/></td>
											<td class="contenttext">
												&nbsp;
												<input type="hidden" id="<c:out value='${compTran.id}' />Cat" value="<c:out value='${compTran.category.id}' />" />
												<input type="hidden" id="<c:out value='${compTran.id}' />CatName" value="<c:out value='${compTran.category.name}' />" /> 
												<input type="hidden" id="<c:out value='${compTran.id}' />Amt" value="<c:out value='${compTran.amount}' />" />

												<input type="hidden" id="<c:out value='${compTran.id}' />CompTranParentId" value="<c:out value='${tran.id}' />" />
												<input type="hidden" id="<c:out value='${compTran.id}' />CompTranId" value="<c:out value='${compTran.id}' />" />													<input type="hidden" id="<c:out value='${compTran.id}' />CompTranCatId" value="<c:out value='${compTran.category.id}' />" />
												<input type="hidden" id="<c:out value='${compTran.id}' />CompTranCatName" value="<c:out value='${compTran.category.name}' />" />
												<input type="hidden" id="<c:out value='${compTran.id}' />CompTranAmt" value="<c:out value='${compTran.amount}' />" />
												<input type="hidden" id="<c:out value='${compTran.id}' />CompTranNote" value="<c:out value='${compTran.note}' />" />
											</td>
										</tr>	
										<c:set var="counter" scope="page" value="${counter+1}"/>	    						    									    			
			    					</c:forEach>												
<%-- 

End child transaction section

--%>																									    						    									    			
			    					</c:forEach>
								</tbody>
							</table>	
							
  		<script src='js/tablesort.min.js'></script>

		<script>
  			new Tablesort(document.getElementById('myTable'), {
  				descending: true
			});
		</script>								
					
							<input type="submit" value="Save" id="saveButton" <c:if test="${saveButtonDisabled}">disabled="true"</c:if> class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />    			
			    			</form>
		    			</div>
		    					    				
		    		</div>
		    	</div>
			</div>	  
			<jsp:include page='Footer.jsp' flush="true" />  
		</div>	
				
 <div id="dialog-form-composite-transaction" title="Create composite transaction">
  <p class="transactionCompositeText"></p>
 
  <form>
  <fieldset><legend></legend>
    <label for="transactionAmount">Amount</label>
    <input type="text" name="transactionAmount" id="transactionAmount" class="text ui-widget-content ui-corner-all" />
    <label for="transactionCategory">Category</label>
    <select name="transactionCategory" id="transactionCategory" > 	
    	<c:forEach var="category" items = "${allCategories}">
			<option value="<c:out value='${category.id}' />"><c:out value='${category.name}' /></option>
		</c:forEach>										
	</select>
	<label for="transactionNote">Note</label>
    <input type="text" name="transactionNote" id="transactionNote" class="text ui-widget-content ui-corner-all" />
    <input type="button" name="addTransactionButton" id="addTransactionButton" value="Add" 
    	class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />	
  </fieldset>  
  </form>
<div id="composite-transaction-contain" class="ui-widget">
  <h2>Existing Budgets:</h2>
  	<form id="composite-transaction" action="/fm/secured/SaveTransactions" method="post"> 
  		<input type="hidden" name="c" id="c" value="y" />
	  <table id="compositeTransactionTable" class="ui-widget ui-widget-content dialogtable">
	    <thead>
	      <tr class="ui-widget-header ">
	        <th>Amount</th>
	        <th>Category</th>
	        <th>Note</th>
	      </tr>
	    </thead>
	    <tbody>
	    </tbody>
	  </table>
	  </form>
</div>  
</div>
	</body>
</html>